package com.crpc.core.discovery;

import com.crpc.common.constant.Constant;
import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.discovery.Impl.NacosRegistry;
import com.crpc.core.discovery.Impl.ZookeeperRegistry;
import lombok.Data;

/**
 * @author CLOUD
 * @version 1.0
 * @description:
 * @date 2023/9/7 13:49
 */
@Data
public class RegistryConfig {
    //定义连接的url zookeeper://127.0.0.1:21810,redis://127.0.0.1:6379
    private String connectString;

    public RegistryConfig(String connectString) {
        this.connectString = connectString;
    }

    //简单工厂
    public Registry getRegistry() {
        String registryType = getRegistryType(connectString, true).toLowerCase().trim();
        if (registryType.equals("zookeeper")) {
            String host = getRegistryType(connectString, false);
            return new ZookeeperRegistry(host, Constant.DEFAULT_TIME_OUT);
        } else if (registryType.equals("nacos")) {
            String host = getRegistryType(connectString, false);
            return new NacosRegistry(host, Constant.DEFAULT_TIME_OUT);
        }
        throw new CrpcException(CrpcExceptionEnums.REGISTRY_TYPE);
    }

    public String getRegistryType(String connectString, boolean ifType) {
        String[] typeAndHost = connectString.split("://");
        if (typeAndHost.length != 2) {
            throw new CrpcException(CrpcExceptionEnums.REGISTRY_TYPE);
        }
        if (ifType) {
            return typeAndHost[0];
        } else {
            return typeAndHost[1];
        }
    }
}
